<?php

/**
 * Helper class for work with images uploaded to client application.
 */
abstract class GG_API_UploadedImages {

	/**
	 * Reads uploaded image files and encode them so they can be passed to
	 * API method.
	 *
	 * @param string $imagesParamName Name of parameter used to upload image
	 *     files with HTML input tag and type=file.
	 *
	 * @return array Array of encoded contents of uploaded image files.
	 * If no images were uploaded or all uploaded images are invalid then empty
	 * array will be returned.
	 */
	public static function getEncodedDatas($imagesParamName = "images") {
		$imageDatas = array();
		$files = array();

		// Convert info about uploaded files to better (loop-frendly) array structure.
		foreach ($_FILES as $file) {
			$fileName = $file["name"];
			if (is_array($fileName)) {
				foreach ($fileName as $key => $value) {
					$files[] = array(
						"name" => $file["name"][$key],
						"type" => $file["type"][$key],
						"tmp_name" => $file["tmp_name"][$key],
						"error" => $file["error"][$key],
						"size" => $file["size"][$key]
					);
				}
			} else {
				$files[] = $file;
			}
		}

		if (count($files) > 0) {
			foreach ($files as $file) {
				// If uploaded file is valid image file.
				if (self::isValidImageFile($file)) {
					$imageDatas[] = self::readAndEncode($file["tmp_name"]);
				}
			}
		}

		return $imageDatas;
	}

	/**
	 * Test by file extension if it is allowed image file.
	 *
	 * @param array Array that represents uploaded image file in $_FILES.
	 *
	 * @return bool
	 */
	public static function isValidImageFile($file = array()) {
		// Allow only images to upload.
		$allowedExtensions = array("bmp", "jpg", "jpeg", "jpe", "gif", "png");
		if ($file["tmp_name"] > "") {
			if (in_array(end(explode(".", strtolower($file["name"]))),
					$allowedExtensions)) {
				return true;
			}
		}
		return false;
	}

	// TODO: api: refactor: this method can be moved to Files::readAndEncode(). (n, redundant)
	/**
	 * Read and prepare (encode) contentn of image to be passed as parameter to API
	 * method call.
	 *
	 * @param string $filename Name of the file to read. Can be URL or path to
	 * file on the System.
	 *
	 * @return string
	 */
	public static function readAndEncode($filename) {
		$file = file_get_contents($filename);
		if ($file) {
			$file = base64_encode($file);
			$file = urlencode($file);
		} else {
			$file = "";
		}
		return $file;
	}
}

?>
